package org.snail.common;

import com.monitorjbl.xlsx.StreamingReader;
import lombok.NonNull;
import lombok.extern.log4j.Log4j;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.snail.constant.WorkSheetConstant;
import org.snail.excel.annotation.ExcelSheetReaderProcessor;
import org.snail.excel.annotation.ExcelSheetWriteProcessor;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Log4j
public class ExcelUtils { //test

    private static final Logger LOGGER = Logger.getLogger(ExcelUtils.class);


    /**
     * 判断审批单中是否有请假数据
     *
     * @param leaveStr
     * @return
     */
    public static boolean isLeave(String leaveStr) {
        boolean flag = false;
        if (leaveStr.contains(WorkSheetConstant.APPROVAL_WORK_FREE_TYPE) || leaveStr.contains(WorkSheetConstant.APPROVAL_OUT_TYPE)
                || leaveStr.contains(WorkSheetConstant.APPROVAL_OVERTIME_FREE_TYPE) || leaveStr.contains(WorkSheetConstant.APPROVAL_SICKLEAVE_TYPE)
                || leaveStr.contains(WorkSheetConstant.APPROVAL_YEAR_FREE_TYPE) || leaveStr.contains(WorkSheetConstant.APPROVAL_OUT_BUSSINESS)
                ) {
            flag = true;
        }
        return flag;
    }

    public static boolean isOverWork(String leaveStr) {
        boolean flag = false;
        if (leaveStr.contains(WorkSheetConstant.APPROVAL_OVERTIME_TYPE)) {
            flag = true;
        }
        return flag;
    }


    /**
     * 用Excel导入生成List
     *
     * @param file     传入的考勤Excel
     * @param pathHome 路径
     * @param excelObj 上传文件所需的文件表格对象
     * @return aliWorkList 返回的是一个含有考勤对象的List
     */
    public static List getListFromExcel(CommonsMultipartFile file, String pathHome, Class excelObj, int startColums) {
        FileInputStream input = null;
        BufferedInputStream bufferedInputStream = null;
        List sheetList = null;
        Sheet sheet = null;
        HSSFWorkbook hb = null;
        Workbook wb = null;
        try {
            File serverFile = transferToServer(file, pathHome);
            int a = 0;
            if (null != serverFile) {
                //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
                input = new FileInputStream(serverFile);  //读取的文件路径
                bufferedInputStream = new BufferedInputStream(input);
                String excelType = file.getContentType();

                if ("application/vnd.ms-excel".equals(excelType)) {
                    POIFSFileSystem fs = new POIFSFileSystem(input);
                    hb = new HSSFWorkbook(fs);
                    sheet = hb.getSheetAt(0);
                } else if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(excelType)) {   //xsxl格式
                    bufferedInputStream = new BufferedInputStream(input);
//                    wb = new XSSFWorkbook(bufferedInputStream);
                    wb = StreamingReader.builder()
                            .rowCacheSize(100)  //缓存到内存中的行数，默认是10
                            .bufferSize(4096)  //读取资源时，缓存到内存的字节大小，默认是1024
                            .open(bufferedInputStream);          //打开资源，必须，可以是InputStream或者是File，注意：只能打开XLSX格式的文件
                    sheet = wb.getSheetAt(0);
                }
                ExcelSheetReaderProcessor processor = new ExcelSheetReaderProcessor();
                //读取数据
                sheetList = processor.readFromExcelSheet(sheet, startColums, excelObj);
            }
        } catch (FileNotFoundException e) {
            LOGGER.error("找不到文件！", e);
        } catch (IOException e) {
            LOGGER.error("文件转为List对象失败！");
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                LOGGER.error(e);
            }
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                LOGGER.error(e);
            }
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                LOGGER.error(e);
            }
            try {
                if (hb != null) {
                    hb.close();
                }
            } catch (IOException e) {
                LOGGER.error(e);
            }

        }
        return sheetList;
    }


    /**
     * 上传文件到服务器
     *
     * @param file     文件
     * @param pathHome 上传目录
     * @return
     */
    public static synchronized  File  transferToServer(CommonsMultipartFile file, String pathHome) {
        File serverFile = null;
        try {
            LOGGER.info("fileName：" + file.getOriginalFilename());
            String path = pathHome + "\\" + new Date().getTime() + "_" + file.getOriginalFilename();
            serverFile = new File(path);
            //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
            if (!serverFile.exists()) {
                serverFile.mkdirs();
            }
            file.transferTo(serverFile);
        } catch (FileNotFoundException e) {
            LOGGER.error("找不到文件！", e);
        } catch (IOException e) {
            LOGGER.error(e);
        }
        return serverFile;
    }

    /**
     * 写出对象到Excel
     *
     * @param excelResult 写出的对象
     * @param startRow    起始行
     * @return
     */
    public static File writeToExcel(String outfilePath, List excelResult, int startRow, @NonNull String sheetName) {
        File outfile = null;
        OutputStream out = null;
        try {
            XSSFWorkbook outWorkbook = new XSSFWorkbook();
            //第二部，在workbook中创建一个sheet对应excel中的sheet
            XSSFSheet outSheet = outWorkbook.createSheet(sheetName);
            new ExcelSheetWriteProcessor().writeToExcelSheet(outSheet, startRow, excelResult);

            outfile = new File(outfilePath);
            out = new FileOutputStream(outfile);
            outWorkbook.write(out);
        } catch (IOException e) {
            LOGGER.error(e);
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                LOGGER.error(e);
            }
        }
        return outfile;
    }


//    /**
//     * 根据dateStr，转换成日期使用
//     */
//    public static Date setAttendanceDate(@NonNull String dateStr) {
//        //dateStr 18-05-12 星期六，转换成date类型
//        String dateDemo = dateStr.split(" ")[0];         // 将18-05-12取出
//        String datePattern = "20" + dateDemo;             //虽然有些简单粗暴，但是还是将代码强行转为2018-05-12
//        SimpleDateFormat strToDate = new SimpleDateFormat("yyyy-MM-dd");
//
//        Date attendanceDate = null;
//        try {
//            attendanceDate = strToDate.parse(datePattern);
//        } catch (ParseException e) {
//            log.error("=======转换类型操作异常", e);
//            log.error("=======转换类型操作异常", e);
//        }
//        return attendanceDate;
//    }
}
